import 'package:fish_redux/fish_redux.dart';
import 'package:wowhy/service_locator.dart';
import 'package:wowhy/services/admin_user_service.dart';
import 'package:wowhy/services/navigate_service.dart';
import 'package:wowhy/utils/message.dart';
import '../action.dart';
import 'action.dart';
import 'state.dart';

Effect<AdminUserItemState> buildEffect() {
  return combineEffects(<Object, Effect<AdminUserItemState>>{
    AdminUserItemAction.onDetail: _onDetail,
    AdminUserItemAction.onEdit: _onEdit,
    AdminUserItemAction.onRemove: _onRemove,
  });
}

void _onDetail(Action action, Context<AdminUserItemState> ctx) async {
  final result = await getIt<NavigateService>().pushNamed(
    'admin_user_edit',
    arguments: {
      'id': ctx.state.model.id,
      'mode': 'detail'
    },
  );

  if (result != null) {
    ctx.dispatch(AdminUserItemActionCreator.edit(result));
  }
}

void _onEdit(Action action, Context<AdminUserItemState> ctx) async {
  final result = await getIt<NavigateService>().pushNamed(
    'admin_user_edit',
    arguments: {
      'id': ctx.state.model.id,
      'mode': 'edit'
    },
  );

  if (result != null) {
    ctx.dispatch(AdminUserItemActionCreator.edit(result));
  }
}

void _onRemove(Action action, Context<AdminUserItemState> ctx) async {
  if ((await MessageUtil.confirm(ctx.context, '是否删除该数据？')) ==
      AlertActionResult.yes) {
    try {
      await MessageUtil.blocking(ctx.context, () {
        return AdminUserService.instance.removeById(ctx.state.model.id);
      });
      ctx.dispatch(AdminUserListActionCreator.remove(ctx.state.model));
    } catch (ex) {
      // nothing
    }
  }
}
